package at.tugraz.akm.forume.adapter;

import java.util.ArrayList;

import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import at.tugraz.akm.forume.R;
import at.tugraz.akm.forume.ThreadView;
import at.tugraz.akm.forume.bean.Thread;

public class ThreadAdapter extends ArrayAdapter<Thread> {

	ArrayList<Thread> threads;
	LayoutInflater vi;

	public ThreadAdapter(Context context, int textViewResourceId,
			ArrayList<Thread> objects) {
		super(context, textViewResourceId, objects);
		this.threads = objects;
		vi = (LayoutInflater) getContext().getSystemService(
				Context.LAYOUT_INFLATER_SERVICE);
	}

	@Override
	public int getCount() {
		return threads.size();
	}

	public static class ViewHolder {
		public TextView title;
		public TextView count;
	}

	public View getView(int position, View convertView, ViewGroup parent) {
		View v = convertView;

		final ViewHolder holder;

		if (v == null) {
			v = vi.inflate(R.layout.thread_row, null);
			holder = new ViewHolder();
			holder.title = (TextView) v.findViewById(R.id.title);
			holder.count = (TextView) v.findViewById(R.id.count);

			v.setTag(holder);
		} else {
			holder = (ViewHolder) v.getTag();
		}

		final Thread thread = threads.get(position);
		holder.title.setText(thread.getTitle());

		if (thread.getNum_replies() >= 0) {
			holder.count.setText("" + thread.getNum_replies());
		} else {
			holder.count.setVisibility(View.INVISIBLE);
		}

		v.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				arg0.getContext().startActivity(
						new Intent(getContext(), ThreadView.class).putExtra(
								"id", thread.getId()));
			}
		});

		return v;
	}

}
